$(function () {
    $("#jqGrid").Grid({
        url: '../inspectionoption/list',
        colModel: [
            {label: '选项编号', name: 'optionCode', index: 'OPTION_CODE', width: 80},
            {label: '选项名称', name: 'optionName', index: 'OPTION_NAME', width: 80},
            {label: '设备供应商', name: 'devSupplyName', index: 'DEV_SUPPLY', width: 80},
            {label: '设备类型', name: 'devTypeNameS', index: 'devTypeNameS', width: 80},
            {label: '设备类型', name: 'devTypeS', index: 'DVE_TYPE_S', width: 80, hidden: true},
            {label: '检查标准', name: 'checkNorm', index: 'CHECK_NORM', width: 80},
            {label: '判断标准', name: 'judNorm', index: 'JUD_NORM', width: 80},
            {label: '方法手段', name: 'methodMeans', index: 'METHOD_MEANS', width: 80},
            {label: '选项备注', name: 'optionRemark', index: 'OPTION_REMARK', width: 80},
            {name: 'DEV_SUPPLY', hidden: true},
            {label: 'id', name: 'id', index: 'ID', key: true, hidden: true},
        ]
    });
    vm.getSelectTreeShow();
});



var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "typeCode",
            pIdKey: "typePid",
            rootPId: -1
        },
        key: {
            url: "nourl",
            name: "typeName" //name 与 typeName 绑定
        },
    },
    callback: {
        beforeCheck: true,
    }

};

//类型树-首页加载增加查询方法
var typeSetting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "typeCode",
            pIdKey: "typePid",
            rootPId: -1
        },
        key: {
            url: "nourl",
            name: "typeName" //name 与 typeName 绑定
        },
    },
    callback: {
        beforeCheck: true,
        beforeClick: outTreeCheck
    }
};

function outTreeCheck(e, treeObj, treeNode) {
    //此处treeNode 为当前节点
    var str = '';
    str = getAllChildrenNodes(treeObj, str);
    // 加上被选择节点自己
    str = str + ',' + treeObj.typeCode;
    // 去掉最前面的逗号
    var ids = str.substring(1, str.length);

    vm.q.devType = ids;
    vm.query();
}


// 递归，获取所有子节点
function getAllChildrenNodes(treeNode, result) {
    if (treeNode.isParent) {
        var childrenNodes = treeNode.children;
        if (childrenNodes) {
            for (var i = 0; i < childrenNodes.length; i++) {
                result += ',' + childrenNodes[i].typeCode;
                result = getAllChildrenNodes(childrenNodes[i], result);
            }
        }
    }
    return result;
}

let vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        inspectionOption: {
            devTypeNameS: '',
            devSupply: '',
            devTypeS: '',
            delFlag: '',
            optionRemark: '',
            checkNorm: '',
            methodMeans: '',
            optionType: '',
            optionName: '',
            id: '',
        },
        ruleValidate: {
            name: [
                {required: true, message: '名称不能为空', trigger: 'blur'}
            ]
        },
        facType:'', //厂家名称
        q: {
            name: '',
            devType:'',
        }
    },
    methods: {
        loadFacType:function(){
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择厂家',
                content: '../sys/factorytype_choose.html?type=0',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getFacType();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        layer.close(index);
                        vm.inspectionOption.devSupply = res.id;
                        vm.inspectionOption.devSupplyName = res.faName;
                        vm.facType = res.faName;
                    }
                }
            })
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.inspectionOption = {
                devTypeNameS: '',
                devSupply: '',
                devTypeS: '',
                delFlag: '',
                optionRemark: '',
                checkNorm: '',
                methodMeans: '',
                optionType: '',
                optionName: '',
                id: '',
            };
            vm.facType ="";
            vm.getTreeShow();
        },
        update: function (event) {
            let id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.getTreeShow();
            vm.getInfo(id);
        },
        saveOrUpdate: function (event) {
            let url = vm.inspectionOption.id == (null || '') ? "../inspectionoption/save" : "../inspectionoption/update";
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.inspectionOption),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            let ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../inspectionoption/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../inspectionoption/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.inspectionOption = r.inspectionOption;
                    vm.facType = r.inspectionOption.devSupplyName;
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            let page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'name': vm.q.name,'devType':vm.q.devType},
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        reloadSearch: function () {
            vm.q = {
                name: '',
                devType:''
            };
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        getTreeShow: function () {
            //加载分类树
            Ajax.request({
                url: '../devtype/listAll',
                async: true,
                successCallback: function (r) {
                    ztree = $.fn.zTree.init($("#categoryTree"), setting, r.list);
                    var node = ztree.getNodeByParam("typeCode", vm.inspectionOption.devTypeNameS);
                    if (node) {
                        ztree.selectNode(node);
                        if(node.devTypeName){
                            vm.inspectionOption.devTypeNameS = node.devTypeName;
                        }else{
                            vm.inspectionOption.devTypeNameS = '无';
                        }

                    } else {
                        node = ztree.getNodeByParam("id", "0");
                        ztree.selectNode(node);
                    }

                    // ztree.expandAll(true);
                }
            });
        },
        devTypeShow: function () {
            openWindow({
                title: "选择设备类型",
                area: ['300px', '450px'],
                content: jQuery("#categoryLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    vm.inspectionOption.devTypeS = node[0].id;
                    vm.inspectionOption.devTypeNameS = node[0].typeName;
                    layer.close(index);
                }
            });
        },
        imports:function(){

        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传.xls或.xlsx的文件。'
            });
        },
        handleBeforeUpload: function() {
            this.$refs.uploadFile.clearFiles();
            this.$Loading.start();
        },
        handleSuccess: function (res, file) {
            if(!res.err) {
                this.$Loading.finish();
                alert('导入成功', function (index) {
                    vm.reload();
                });
            } else {
                this.$Loading.error();
                this.$Notice.error({
                    title: '导入失败',
                    desc: res.msg
                })
            }
        },
        handleError: function (err, file) {
            alert('导入失败');
        },
        getSelectTreeShow: function () {
            //加载分类树
            Ajax.request({
                url: '../devtype/listAll',
                async: true,
                successCallback: function (r) {
                    deptZtree = $.fn.zTree.init($("#devTypeTree"), typeSetting, r.list);
                    // deptZtree.expandAll(true);
                }
            });
        },
    }
});
